#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Script to parse test.guiguider file and extract all FrontJson nodes with full content.
Each node is saved as a separate JSON file in the 'json' directory.
"""

import json
import os
import sys


def parse_full_frontjson(input_file, output_dir):
    """
    Parse the guiguider file and save each FrontJson node with full content to a separate JSON file.
    """
    try:
        with open(input_file, 'r', encoding='utf-8') as f:
            data = json.load(f)
        
        # Create output directory if it doesn't exist
        os.makedirs(output_dir, exist_ok=True)
        
        # Extract FrontJson array
        frontjson_data = data.get('FrontJson', [])
        
        # Process each node in FrontJson
        for node in frontjson_data:
            # Get the node name
            node_name = node.get("name")
            
            # Save to JSON file if name exists
            if node_name:
                output_file = os.path.join(output_dir, f'{node_name}.json')
                with open(output_file, 'w', encoding='utf-8') as f:
                    json.dump(node, f, ensure_ascii=False, indent=2)
        
        print(f"Successfully parsed {input_file} and saved all FrontJson nodes to {output_dir} directory")
    except FileNotFoundError:
        print(f"Error: File {input_file} not found.")
        sys.exit(1)
    except json.JSONDecodeError as e:
        print(f"Error: Failed to decode JSON from {input_file}: {e}")
        sys.exit(1)
    except Exception as e:
        print(f"Error: {e}")
        sys.exit(1)


if __name__ == "__main__":
    if len(sys.argv) != 3:
        print("Usage: python parse_full_frontjson.py <input_file> <output_dir>")
        sys.exit(1)
    
    input_file = sys.argv[1]
    output_dir = sys.argv[2]
    
    parse_full_frontjson(input_file, output_dir)